<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-radio-group v-model="searchParams.auditState" class="item-gap" size="small" @change="onStateChange">
						<el-radio-button v-for="item in auditStateList" :key="item.id" :label="item.id">
							<el-badge v-if="item.id === 0 && unHandlerCount" :value="unHandlerCount" :max="99">
								<span class="margin-right-20">{{ item.name }}</span>
							</el-badge>
							<span v-else class="margin-right-10">{{ item.name }}</span>
						</el-radio-button>
					</el-radio-group>
					<el-button size="small" type="success" @click="onBatchBtn">批量处理</el-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.processCodes" multiple collapse-tags :multiple-limit="3" value-key-name="code" :option-list="processList" placeholder="工序" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种编号或名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台编号或名称" size="small" class="search-bar-item-size1 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.prdNoticeCode" placeholder="生产通知单号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.productOrderCode" placeholder="生产订单号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<!--<jk-search-input v-model="searchParams.specSheetCode" placeholder="工艺单号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />-->
					<!--<jk-select v-model="searchParams.auditState" :option-list="auditStateList" placeholder="状态" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="jkTable"
				border
				:span-method="mergeColMethod"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 20"
				@checkbox-change="onCheckChange"
			>
				<vxe-column type="checkbox" width="60" align="center"></vxe-column>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<el-tag v-if="item.keyName === 'specSheetCode'" :class="scope.row.specSheetCode ? '' : ''" :type="scope.row.specSheetCode ? 'primary' : 'warning'">{{ scope.row.specSheetCode || '-' }}</el-tag>
						<technology-task-state-bar v-else-if="item.keyName === 'auditState'" :status="scope.row.auditState"></technology-task-state-bar>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="180">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button :disabled="scope.row.auditState !== 0" size="mini" icon="el-icon-remove-outline" type="warning" class="item-gap" @click="onIgnoreBtn(scope.row)">忽略</jk-button>
							<jk-button size="mini" icon="el-icon-edit-outline" type="primary" @click="onEditBtn(scope.row)">处理</jk-button>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:permission-prefix="prefix"
			:data-id="checkArr"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        workforcemanagementShiftDelete
    } from '../../../api/schedule/shift';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { spinSpecSheetTaskIgnore, spinSpecSheetTaskPage } from '../../../api/production/xsNotice';
    import { technologyTaskStateList } from '../../../utils/jk/status-option-list';
    import technologyTaskStateBar from './technology-task-state-bar';
    import { mapState } from 'vuex';
    export default {
        name: 'TechnologyTask',
        components: {
            technologyTaskStateBar,
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        computed: {
            ...mapState({
                userProcessInfo: state => state.user.userProcess
            })
        },
        data() {
            return {
                prefix: 'workforcemanagement:shift',
                unHandlerCount: 0,
                apiItem: {
                    'page': spinSpecSheetTaskPage,
                    'delete': workforcemanagementShiftDelete
                },
                auditStateList: technologyTaskStateList,
                detailDialogState: false,
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                processList: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    machineNameOrCode: '',
                    productOrderCode: '',
                    prdNoticeCode: '',
                    specSheetCode: '',
                    productNameOrCode: null,
                    processCodes: [],
                    auditState: 0
                },
                checkArr: []
            };
        },
        methods: {
            onStateChange() {
                this.searchParams.pageNo = 1;
                this.getListRequest();
            },
            onBatchBtn() {
                const processArr = Array.from(new Set(this.checkArr.map(x => x.processId)));
                if (processArr.length > 1) {
                    tipsBar(this, 'custom', 'warning', '批量处理，只能选择同工序的任务!');
                } else {
                    this.saveDialogState = true;
                }
            },
            onCheckChange({ records }) {
                this.checkArr = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
            },
            onIgnoreBtn({ id }) {
                spinSpecSheetTaskIgnore({ id }).then(res => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                    }
                });
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['typeName']; // 根据字段判断数据相同的合并
                const cellValue = row[column.property];
                if (cellValue && fields.includes(column.property)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.property] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.property] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.detailDialogState = e;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    // this.dataId = [];
                }
                this.saveDialogState = e;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.getUnHandlerTotalCountRequest();
                return this.apiItem.page(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.checkArr = [row];
                this.saveDialogState = true;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem.exportExcel(params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getUnHandlerTotalCountRequest() {
                this.apiItem.page({
                    auditState: 0,
                    processCodes: this.searchParams.processCodes
                }).then(res => {
                    if (res.data.status === 200) {
                        this.unHandlerCount = res.data.count;
                    }
                });
            },
            async getDependentData() {
                this.processList = this.$store.state.user.userProcess.processList;
                await this.getMenuColumnListRequest();
                await this.getUnHandlerTotalCountRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.$set(this.searchParams, 'processCodes', this.$store.state.user.userProcess.processList ? this.$store.state.user.userProcess.processList.map(x => x.code) : []);
            this.getDependentData();
        }
    };
</script>
